﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Gameplay.CharacterFramework
{
    public class ComponentManager:MonoBehaviour
    {
        private  List<CoreComponent> coreComponents = new List<CoreComponent>();
        public void LogicUpdate() 
        {
            foreach (var component in coreComponents)
            {
                component.LogicUpdate();
            }
        }
        public void PhysicsUpdate() 
        {
            foreach (var component in coreComponents)
            {
                component.PhysicsUpdate();
            }
        }

        public void AddComponent(CoreComponent component) 
        {
            if (!coreComponents.Contains(component)) 
            {
                coreComponents.Add(component);
            }
        }

        public T GetCoreComponent<T>() where T : CoreComponent
        {
            T comp= coreComponents.OfType<T>().FirstOrDefault();
            if(comp) return comp;
            comp =GetComponentInChildren<T>();
            if(comp) return comp;

            Debug.LogWarning($"{typeof(T)} 组件不存在在 {transform.parent.name}");
            return null;
        }

        //public static CoreComponent GetCoreComponent(Type componentType) 
        //{
        //    foreach(var component in coreComponents) 
        //    {
        //        if(component.GetType()== componentType) 
        //        {
        //            return component;
        //        }
        //    }
        //    Debug.LogWarning($"{componentType} 不存在");
        //    return null;
        //}
    }
}
